﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace JavacDemo
{
    public partial class Form1 : Form
    {
        public static string ExeCommand(string cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = false; //true表示不显示黑框，false表示显示dos界面
            string strOutput = null;
            try
            {
                p.Start();
                //要执行的dos命令  p.StandardInput.WriteLine("");
                p.StandardInput.WriteLine(cmd);

                p.StandardInput.WriteLine("exit");
                
            }
            catch (Exception)
            {
                return "error";
            }

            StringBuilder output = new StringBuilder();
            while (!p.HasExited)
            {
                output.Append(p.StandardOutput.ReadToEnd()+p.StandardError.ReadToEnd());
                //error.Append(p.StandardOutput.ReadToEnd());

            }
            p.Close();

            return output.ToString();

        }
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCompile_Click(object sender, EventArgs e)
        {
            string code = "";
            code += "import java.util.*;";
            code+="public class Main{";
            code+=txtCode.Text;
            code += "}";
            File.WriteAllText("Main.java", code);
   

            string res = ExeCommand("java -jar D:\\Dropbox\\GuoLiang\\final\\test\\javac.jar Main.java").Substring(140);
            res=Regex.Replace(res, @"C:\\Users\\Administrator\\Desktop\\JavacDemo\\JavacDemo\\bin\\Debug", "");
            txtOutput.Text = res;
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            string res = ExeCommand("java Main").Substring(140);
            res = Regex.Replace(res, @"C:\\Users\\Administrator\\Desktop\\JavacDemo\\JavacDemo\\bin\\Debug", "");
            txtOutput.Text = res;
           
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string code = "";
            string[] names = {"blockexp.txt","define.txt", "access.txt", "comprehension.txt", "add.txt", "mul.txt", "qsort.txt" };
            txtCode.Text=File.ReadAllText(names[comboBox1.SelectedIndex]);
        }


    }
}
